/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package gestionmagasins_aspectj_junit_patterns.forms;

import gestionmagasins_aspectj_junit_patterns.model.CatalogueArticles;
import gestionmagasins_aspectj_junit_patterns.model.Taille;
import gestionmagasins_aspectj_junit_patterns.model.Taxe;
import gestionmagasins_aspectj_junit_patterns.model.Article;
import gestionmagasins_aspectj_junit_patterns.model.ArticleNeuf;
import gestionmagasins_aspectj_junit_patterns.model.CatalogueVente;
import gestionmagasins_aspectj_junit_patterns.model.TypeArticle;
import gestionmagasins_aspectj_junit_patterns.model.Usager;
import gestionmagasins_aspectj_junit_patterns.model.Vente;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;

/**
 *
 * @author Michael
 */
public class ManageProductsJFrame extends CustomJFrame {

    private boolean isNew;
    private boolean requireSave;
    private boolean isLoadingDetail;
    private Article currentArticle;
    private DefaultListModel<Article> productsList;
    private CatalogueArticles articles;
    private ArrayList<Taille> tailles;
    private ArrayList<Taxe> allTaxes;
    private DefaultComboBoxModel<Taxe> taxes;
    private DefaultListModel<Taxe> taxesOfArticle;
    
    /**
     * Creates new form ManageProductsJFrame
     */
    ManageProductsJFrame(MainMenuJFrame mainMenu, ArrayList<Taille> tailles, ArrayList<Taxe> allTaxes) 
    {
        super(mainMenu);
        
        initComponents();
        this.initKeyListeners();
        
        this.articles = CatalogueArticles.getCatalogueArticles();
        this.tailles = tailles;
        this.allTaxes = allTaxes;
        
        sizeJComboBox.setModel(new DefaultComboBoxModel(tailles.toArray()));
      
        productsList = new DefaultListModel<Article>();
        productsJList.setModel(productsList);
        
        productsJList.addListSelectionListener(listProductSelectItemListener);
        taxesJList.addListSelectionListener(listTaxeSelectItemListener);
        
        taxesOfArticle = new DefaultListModel<Taxe>();
        taxesJList.setModel(taxesOfArticle);
        
        codeJText.getDocument().addDocumentListener(documentListener);
        nameJText.getDocument().addDocumentListener(documentListener);
        descriptionJText.getDocument().addDocumentListener(documentListener);
        priceJSpinner.addChangeListener(changeListener);
        quantityJSpinner1.addChangeListener(changeListener);
        
        chargerListe();
        
        //RefreshLstClient(clients.getClients());
        //GestionIdentification(false);
    }

    private final DocumentListener documentListener = new DocumentListener()
    {
        @Override
        public void insertUpdate(DocumentEvent e) 
        {
            setRequireSave(true);
        }

        @Override
        public void removeUpdate(DocumentEvent e) 
        {
             setRequireSave(true);
        }

        @Override
        public void changedUpdate(DocumentEvent e) 
        {
        }
    };
    
    private final ChangeListener changeListener = new ChangeListener()
    {
        @Override
        public void stateChanged(ChangeEvent e)
        {
         setRequireSave(true);   
        }
    };
    
    private final ListSelectionListener listProductSelectItemListener = new ListSelectionListener() 
    {
        @Override
        public void valueChanged(ListSelectionEvent evt) 
        {
            if(productsJList.getSelectedValue() != null) {
                currentArticle = (Article)productsJList.getSelectedValue();
                deleteProductJButton.setEnabled(true);
            }
            else {
                deleteProductJButton.setEnabled(false);
            }
            chargerDetail();
        }
    };
    
    private final ListSelectionListener listTaxeSelectItemListener = new ListSelectionListener() 
    {
        @Override
        public void valueChanged(ListSelectionEvent evt) 
        {
           Taxe selectedTaxe = (Taxe)taxesJList.getSelectedValue();
           if(selectedTaxe != null){
               removeTaxeJButton.setEnabled(true);
           }
           else {
               removeTaxeJButton.setEnabled(false);
           }
        }
    };
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        createNewProductJButton = new javax.swing.JButton();
        saveProductJButton = new javax.swing.JButton();
        cancelActionJButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        productsJList = new javax.swing.JList();
        deleteProductJButton = new javax.swing.JButton();
        productSearchJText = new javax.swing.JTextField();
        productDetailsJPanel = new javax.swing.JPanel();
        codeJText = new javax.swing.JTextField();
        jLabel11 = new javax.swing.JLabel();
        nameJText = new javax.swing.JTextField();
        jLabel12 = new javax.swing.JLabel();
        descriptionJText = new javax.swing.JTextField();
        jLabel13 = new javax.swing.JLabel();
        jLabel14 = new javax.swing.JLabel();
        sizeJComboBox = new javax.swing.JComboBox();
        jLabel15 = new javax.swing.JLabel();
        jLabel16 = new javax.swing.JLabel();
        quantityJSpinner1 = new javax.swing.JSpinner();
        jScrollPane2 = new javax.swing.JScrollPane();
        taxesJList = new javax.swing.JList();
        addTaxeJButton = new javax.swing.JButton();
        removeTaxeJButton = new javax.swing.JButton();
        taxesJComboBox = new javax.swing.JComboBox();
        priceJSpinner = new javax.swing.JSpinner();
        jLabel17 = new javax.swing.JLabel();
        typeLabel = new javax.swing.JLabel();
        createUsedProductJButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Super Logiciel inc.");

        jLabel1.setFont(new java.awt.Font("Lucida Grande", 1, 18)); // NOI18N
        jLabel1.setText("Gestion des articles");

        jLabel2.setText("Rechercher ");

        createNewProductJButton.setText("Créer neuf");
        createNewProductJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                createNewProductJButtonActionPerformed(evt);
            }
        });

        saveProductJButton.setText("Enregistrer");
        saveProductJButton.setEnabled(false);
        saveProductJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveProductJButtonActionPerformed(evt);
            }
        });

        cancelActionJButton.setText("Annuler");
        cancelActionJButton.setEnabled(false);
        cancelActionJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelActionJButtonActionPerformed(evt);
            }
        });

        productsJList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        productsJList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(productsJList);

        deleteProductJButton.setText("Supprimer");
        deleteProductJButton.setEnabled(false);
        deleteProductJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteProductJButtonActionPerformed(evt);
            }
        });

        productSearchJText.setName(""); // NOI18N
        productSearchJText.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                productSearchJTextKeyPressed(evt);
            }
        });

        productDetailsJPanel.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        productDetailsJPanel.setToolTipText("Identification");

        codeJText.setName("Nom"); // NOI18N

        jLabel11.setText("Code");
        jLabel11.setToolTipText("");

        nameJText.setName("Prénom"); // NOI18N

        jLabel12.setText("Nom");

        descriptionJText.setName("Nom d'utilisateur"); // NOI18N

        jLabel13.setText("Description");

        jLabel14.setText("Prix");

        sizeJComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        sizeJComboBox.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                sizeJComboBoxItemStateChanged(evt);
            }
        });

        jLabel15.setText("Taille");

        jLabel16.setText("Quantité");

        quantityJSpinner1.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(0), Integer.valueOf(0), null, Integer.valueOf(1)));

        taxesJList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        taxesJList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane2.setViewportView(taxesJList);

        addTaxeJButton.setText("+");
        addTaxeJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addTaxeJButtonActionPerformed(evt);
            }
        });

        removeTaxeJButton.setText("-");
        removeTaxeJButton.setToolTipText("");
        removeTaxeJButton.setEnabled(false);
        removeTaxeJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeTaxeJButtonActionPerformed(evt);
            }
        });

        taxesJComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        taxesJComboBox.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                taxesJComboBoxItemStateChanged(evt);
            }
        });

        priceJSpinner.setModel(new javax.swing.SpinnerNumberModel(Double.valueOf(0.0d), Double.valueOf(0.0d), null, Double.valueOf(1.0d)));

        jLabel17.setText("Taxes");

        typeLabel.setText("Code");
        typeLabel.setToolTipText("");

        javax.swing.GroupLayout productDetailsJPanelLayout = new javax.swing.GroupLayout(productDetailsJPanel);
        productDetailsJPanel.setLayout(productDetailsJPanelLayout);
        productDetailsJPanelLayout.setHorizontalGroup(
            productDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(productDetailsJPanelLayout.createSequentialGroup()
                .addGroup(productDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(productDetailsJPanelLayout.createSequentialGroup()
                        .addGap(47, 47, 47)
                        .addGroup(productDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel13)
                            .addComponent(jLabel12)
                            .addComponent(jLabel11)
                            .addComponent(jLabel14)
                            .addComponent(jLabel15))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(productDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(descriptionJText)
                            .addComponent(nameJText)
                            .addComponent(sizeJComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(productDetailsJPanelLayout.createSequentialGroup()
                                .addGroup(productDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(priceJSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(productDetailsJPanelLayout.createSequentialGroup()
                                        .addComponent(codeJText, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(54, 54, 54)
                                        .addComponent(typeLabel)))
                                .addGap(0, 0, Short.MAX_VALUE))))
                    .addGroup(productDetailsJPanelLayout.createSequentialGroup()
                        .addGap(58, 58, 58)
                        .addGroup(productDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel16)
                            .addComponent(jLabel17))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(productDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(productDetailsJPanelLayout.createSequentialGroup()
                                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 235, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(productDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(addTaxeJButton)
                                    .addComponent(removeTaxeJButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(taxesJComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addGroup(productDetailsJPanelLayout.createSequentialGroup()
                                .addComponent(quantityJSpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE)))))
                .addContainerGap())
        );
        productDetailsJPanelLayout.setVerticalGroup(
            productDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(productDetailsJPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(productDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(codeJText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel11)
                    .addComponent(typeLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(productDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(nameJText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel12))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(productDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(descriptionJText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel13))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(productDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel14)
                    .addComponent(priceJSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(productDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(sizeJComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel15))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(productDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel16)
                    .addComponent(quantityJSpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(productDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(productDetailsJPanelLayout.createSequentialGroup()
                        .addGap(1, 1, 1)
                        .addGroup(productDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(addTaxeJButton)
                            .addComponent(taxesJComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(removeTaxeJButton))
                    .addComponent(jLabel17))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        createUsedProductJButton1.setText("Créer occasion");
        createUsedProductJButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                createUsedProductJButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(productSearchJText))
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(16, 16, 16)
                                .addComponent(createNewProductJButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(createUsedProductJButton1)
                                .addGap(18, 18, 18)
                                .addComponent(deleteProductJButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(saveProductJButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cancelActionJButton, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(productDetailsJPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                        .addGap(87, 87, 87))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(productSearchJText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(productDetailsJPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(createNewProductJButton)
                            .addComponent(saveProductJButton)
                            .addComponent(cancelActionJButton)
                            .addComponent(deleteProductJButton)
                            .addComponent(createUsedProductJButton1)))
                    .addComponent(jScrollPane1))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void setRequireSave(boolean require){
        if(!isLoadingDetail){
        requireSave = require;
        saveProductJButton.setEnabled(require);
        cancelActionJButton.setEnabled(require);
        productsJList.setEnabled(!require);
        productSearchJText.setEnabled(!require);
    }
    }
    
    private void updateCurrentArticleExists(){
        
        boolean exist = currentArticle != null;
        codeJText.setEnabled(exist);
        nameJText.setEnabled(exist);
        descriptionJText.setEnabled(exist);
        priceJSpinner.setEnabled(exist);
        quantityJSpinner1.setEnabled(exist);
        sizeJComboBox.setEnabled(exist);
        taxesJComboBox.setEnabled(exist);
        addTaxeJButton.setEnabled(exist && taxesJComboBox.getSelectedItem() != null);
        removeTaxeJButton.setEnabled(exist && taxesOfArticle.size() > 0);
        taxesJList.setEnabled(exist);
        saveProductJButton.setEnabled(exist && requireSave);
        cancelActionJButton.setEnabled(exist && requireSave);
        
    }
    
    private void chargerListe() {
       
        productsList.clear();
        for(Article article : articles.getListe()){
            if(article.getNom().contains(productSearchJText.getText()) ||
                    article.getDescription().contains(productSearchJText.getText()) ||
                    article.getCodeArticle().contains(productSearchJText.getText())){
                productsList.addElement(article);
            }
        }
        selectProduct();
    }
    
    private void selectProduct(){
        if(productsJList.getSelectedValue() == null){
            if(currentArticle != null)
                productsJList.setSelectedValue(currentArticle, true);
            else
                if(productsList.size() > 0)
                    productsJList.setSelectedIndex(0);
        }
        chargerDetail();
        updateCurrentArticleExists();
            
    }
    
    private void chargerDetail(){
        
        isLoadingDetail = true;
        if(currentArticle != null){
        codeJText.setText(currentArticle.getCodeArticle());
        nameJText.setText(currentArticle.getNom());
        descriptionJText.setText(currentArticle.getDescription());
        priceJSpinner.setValue(currentArticle.getPrix());
        quantityJSpinner1.setValue(currentArticle.getQuantiteEnInventaire());
        if(currentArticle.getTaille() != null)
            sizeJComboBox.setSelectedItem(currentArticle.getTaille());
        else
            sizeJComboBox.setSelectedItem(tailles.get(3));
        
        if(currentArticle instanceof ArticleNeuf)
            typeLabel.setText("Neuf");
        else
            typeLabel.setText("Occasion");
        
        taxes = new DefaultComboBoxModel(allTaxes.toArray());
        taxesOfArticle.clear();
        for(Taxe taxe : currentArticle.getTaxes()){
            taxesOfArticle.addElement(taxe);
            taxes.removeElement(taxe);
        }
        taxesJComboBox.setModel(taxes);
            addTaxeJButton.setEnabled(taxes.getSelectedItem() != null);
        }
        else{
            codeJText.setText("");
            nameJText.setText("");
            descriptionJText.setText("");
            priceJSpinner.setValue(0);
            quantityJSpinner1.setValue(0);
            sizeJComboBox.setSelectedItem(tailles.get(3));
            taxesOfArticle.clear();
        }
        isLoadingDetail = false;
    }
    
    private boolean confirmSave(){
        
        if(requireSave){
            int retour = JOptionPane.showConfirmDialog(null, "Voulez-vous sauvegarder avant de continuer?", "Attention", JOptionPane.YES_NO_CANCEL_OPTION);
            if(retour == JOptionPane.YES_OPTION)
                return saveProduct();
            else if(retour == JOptionPane.CANCEL_OPTION)
                return false;
        }
        return true;
    }
    
    private boolean confirmCancel(){
    
        int retour = JOptionPane.showConfirmDialog(null, "Êtes-vous sure de vouloir annuler?", "Attention", JOptionPane.YES_NO_OPTION);
            
        if(retour == JOptionPane.YES_OPTION)
            return true;
        else
            return false;
    }
    
    private boolean confirmDelete(){
        int retour = JOptionPane.showConfirmDialog(null, "Êtes-vous sure de vouloir supprimer l'article?", "Attention", JOptionPane.YES_NO_OPTION);
            
        if(retour == JOptionPane.YES_OPTION)
            return true;
        else
            return false;
    }
    
    private void newProduct(TypeArticle type){
        
        if(confirmSave()){
        productsJList.clearSelection();
        codeJText.requestFocus();
        
        isNew = true;
        currentArticle = articles.creerArticle(type);
        chargerDetail();
        updateCurrentArticleExists();
        setRequireSave(true);
        }
    }
    
    private boolean validateFields(){
        
        boolean valide = true;
        String messageValidation = "";
        
        if(codeJText.getText().isEmpty()){
            messageValidation += "Le champ code article ne doit pas être vide.\n";
            valide = false;
        }
        if(nameJText.getText().isEmpty()){
            messageValidation += "Le champ nom ne doit pas être vide.\n";
            valide = false;
        }
        if(descriptionJText.getText().isEmpty()){
            messageValidation += "Le champ description ne doit pas être vide.\n";
            valide = false;
        }
        if(sizeJComboBox.getSelectedItem() == null){
            messageValidation += "Le champ taille ne doit pas être vide.\n";
            valide = false;
        }

        if(!valide)
            JOptionPane.showMessageDialog(null, messageValidation);
        
        return valide;
    }
    
    private boolean saveProduct(){
        
        if(currentArticle != null && validateFields()){
        currentArticle.setCodeArticle(codeJText.getText());
        currentArticle.setNom(nameJText.getText());
        currentArticle.setDescription(descriptionJText.getText());
        currentArticle.setPrix((double)priceJSpinner.getValue());
        currentArticle.setQuantiteEnInventaire((int)quantityJSpinner1.getValue());
        currentArticle.setTaille((Taille)sizeJComboBox.getSelectedItem());
        
        currentArticle.clearTaxes();
        
        for(Object taxe : taxesOfArticle.toArray()){
             currentArticle.addTaxe((Taxe)taxe);
        }
        
        if(isNew) {
            articles.addArticle(currentArticle);
        isNew = false;
        
        }
        chargerListe();
        productsJList.setSelectedValue(currentArticle, true);
            setRequireSave(false);
            return true;
        }
        return false;
    }
    
    private void cancelAction(){
        
        if(confirmCancel()){
            
        if(isNew){
            currentArticle = null;
            isNew = false;
            selectProduct();
        }
        else
            chargerDetail();
        setRequireSave(false);
    }
    }
    
    private void deleteProduct() {
        boolean isUsed = false;
        
        CatalogueVente ventes = CatalogueVente.getCatalogueVente();
        for(Vente vente :ventes.getVentes()){
            if(vente.getListeArticles().contains(currentArticle)){
               isUsed = true;
            break;
            }
        }
        
        if(!isUsed){
        if(confirmDelete()){
            if(currentArticle != null)
        {
            articles.deleteArticle(currentArticle);
            currentArticle = null;
            chargerListe();
            selectProduct();
        }
    }
        }
        else{
            JOptionPane.showMessageDialog(null, "L'article est utilisé dans une vente. Il est impossible de supprimer l'article.");
        }
    }
    
    private void addTaxe(){
        
        Taxe taxeToAdd = (Taxe)taxesJComboBox.getSelectedItem();
        
        if(!taxesOfArticle.contains(taxeToAdd)){
            taxesOfArticle.addElement(taxeToAdd);
            taxes.removeElement(taxeToAdd);
            setRequireSave(true);
        }
        
    }
    
    private void removeTaxe(){
         Taxe taxeToRemove = (Taxe)taxesJList.getSelectedValue();
        
        if(taxesOfArticle.contains(taxeToRemove)){
            taxesOfArticle.removeElement(taxeToRemove);
            taxes.addElement(taxeToRemove);
            setRequireSave(true);
        }
    }
    
    private void createNewProductJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createNewProductJButtonActionPerformed

        newProduct(TypeArticle.Neuf);
    }//GEN-LAST:event_createNewProductJButtonActionPerformed

    private void saveProductJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveProductJButtonActionPerformed

        saveProduct();
    }//GEN-LAST:event_saveProductJButtonActionPerformed

    private void cancelActionJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelActionJButtonActionPerformed

        cancelAction();
    }//GEN-LAST:event_cancelActionJButtonActionPerformed

    private void deleteProductJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteProductJButtonActionPerformed

        deleteProduct();
    }//GEN-LAST:event_deleteProductJButtonActionPerformed

    private void addTaxeJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addTaxeJButtonActionPerformed
        addTaxe();
    }//GEN-LAST:event_addTaxeJButtonActionPerformed

    private void removeTaxeJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeTaxeJButtonActionPerformed
        removeTaxe();
    }//GEN-LAST:event_removeTaxeJButtonActionPerformed

    private void productSearchJTextKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_productSearchJTextKeyPressed
        if(evt.getKeyCode() == KeyEvent.VK_ENTER)
            chargerListe();
    }//GEN-LAST:event_productSearchJTextKeyPressed

    private void taxesJComboBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_taxesJComboBoxItemStateChanged
       Taxe selectedTaxe = (Taxe)taxesJComboBox.getSelectedItem();
        if(selectedTaxe != null){
            addTaxeJButton.setEnabled(true);
        }
        else{
            addTaxeJButton.setEnabled(false);
        }
    }//GEN-LAST:event_taxesJComboBoxItemStateChanged

    private void sizeJComboBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_sizeJComboBoxItemStateChanged
       setRequireSave(true);
    }//GEN-LAST:event_sizeJComboBoxItemStateChanged

    private void createUsedProductJButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createUsedProductJButton1ActionPerformed
       newProduct(TypeArticle.Occasion);
    }//GEN-LAST:event_createUsedProductJButton1ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addTaxeJButton;
    private javax.swing.JButton cancelActionJButton;
    private javax.swing.JTextField codeJText;
    private javax.swing.JButton createNewProductJButton;
    private javax.swing.JButton createUsedProductJButton1;
    private javax.swing.JButton deleteProductJButton;
    private javax.swing.JTextField descriptionJText;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextField nameJText;
    private javax.swing.JSpinner priceJSpinner;
    private javax.swing.JPanel productDetailsJPanel;
    private javax.swing.JTextField productSearchJText;
    private javax.swing.JList productsJList;
    private javax.swing.JSpinner quantityJSpinner1;
    private javax.swing.JButton removeTaxeJButton;
    private javax.swing.JButton saveProductJButton;
    private javax.swing.JComboBox sizeJComboBox;
    private javax.swing.JComboBox taxesJComboBox;
    private javax.swing.JList taxesJList;
    private javax.swing.JLabel typeLabel;
    // End of variables declaration//GEN-END:variables
}
